﻿using Models.WebChat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Business.Uin
{
    /// <summary>
    /// 消息管理
    /// </summary>
    public class MessageInfoManager
    {
        private static List<MessageInfo> _MessageInfoList = null;
        private static int _Index = 1;
        private static object _Lock = new object();
        static MessageInfoManager()
        {
            _MessageInfoList = new List<MessageInfo>();
            //定时清理消息
            Task.Run(() =>
            {
                while(true)
                {
                    //只保留一天的数据
                    _MessageInfoList = _MessageInfoList.Where(msg => (DateTime.Now - msg.Time).TotalDays < 1).ToList();
                    Thread.Sleep(60000);
                }
            });
        }
        /// <summary>
        /// 插入消息
        /// </summary>
        /// <param name="messageInfo"></param>
        /// <returns></returns>
        public int AddMessageInfo(MessageInfo messageInfo)
        {
            lock (_Lock)
            {
                var tempIndex = _Index++;
                messageInfo.Id = tempIndex;
                _MessageInfoList.Add(messageInfo);
                return tempIndex;
            }
        }
        /// <summary>
        /// 根据消息来源 单元 和 当前用户单元id 获取未读消息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="toUinId"></param>
        /// <returns></returns>
        public List<MessageInfo> GetMessageInfoListByFromUinId(int id,int toUinId)
        {
            return _MessageInfoList.Where(m=>m.From_uin == id&&m.To_uin == toUinId).ToList();
        }
        /// <summary>
        /// 获取目标消息
        /// </summary>
        /// <param name="touin"></param>
        /// <returns></returns>
        public List<MessageInfo>GetMessageInfoList(int touin)
        {
            return _MessageInfoList.Where(m => m.To_uin.Equals(touin)).ToList();
        }
        /// <summary>
        /// 设置消息为已读
        /// （这里是删掉，如果是数据库，可以设为已读）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public MessageInfo SetMessageReaded(int id)
        {
            var msgInfo = _MessageInfoList.Where(m => m.Id == id).FirstOrDefault();
            if (msgInfo != null)
                _MessageInfoList.Remove(msgInfo);
            return msgInfo;

        }



    }
}
